package com.example.testapplication.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testapplication.R;
import com.example.testapplication.bean.Planet;

import java.util.ArrayList;

public class PlanetGridAdapter extends BaseAdapter implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    private Context mContext; // 声明一个上下文对象
    private ArrayList<Planet> mPlanetList; // 声明一个行星信息队列

    // 构造函数
    public PlanetGridAdapter(Context context,ArrayList<Planet> planet_list){
        mContext = context;
        mPlanetList = planet_list;
    }

    @Override
    public int getCount() {
        return mPlanetList.size();
    }

    @Override
    public Object getItem(int i) {
        return mPlanetList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    // 获取指定位置的网格视图
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder;
        if(view == null){
            holder = new ViewHolder(); // 创建一个新的视图持有者
            // 根据布局文件item_grid.xml 转成视图对象
            view = LayoutInflater.from(mContext).inflate(R.layout.item_grid,null);
            holder.gv_icon = view.findViewById(R.id.gv_icon);
            holder.gv_name = view.findViewById(R.id.gv_name);
            holder.gv_desc = view.findViewById(R.id.gv_desc);

            // 将视图保存到转换视图当重
            view.setTag(holder);
        }else{
            holder = (ViewHolder) view.getTag();
        }
        Planet planet = mPlanetList.get(i);
        holder.gv_desc.setText(planet.desc);
        holder.gv_name.setText(planet.name);
        holder.gv_icon.setImageResource(planet.image);
        return view;
    }


    // // 处理网格项的点击事件，由接口OnItemClickListener触发
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        String desc = String.format("您点击了第%d个行星，它的名字时%s",i+1,mPlanetList.get(i).name);
        Toast.makeText(mContext, desc, Toast.LENGTH_SHORT).show();

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
        String desc = String.format("您长按了第%d个行星，它的名字是%s", i + 1,
                mPlanetList.get(i).name);
        Toast.makeText(mContext, desc, Toast.LENGTH_LONG).show();
        return true;

    }

    // 定义一个视图持有者，以边重用网格项的视图资源
    public final class ViewHolder{
        public ImageView gv_icon;
        public TextView gv_name;
        public TextView gv_desc;
    }


}
